package com.finger.forest;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionAddressModel;
import com.finger.forest.model.FireInfoModel;
import com.finger.forest.utils.AndroidUtil;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.Utils;
import com.finger.forest.utils.encode.PrefsUtil;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 火场采集信息
 */
public class CollectionFireOthersActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "CollectionFireOthersAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    @BindView(R.id.etFireLocation)
    EditText etFireLocation;
    @BindView(R.id.tvHaveClouds)
    TextView tvHaveClouds;
    @BindView(R.id.tvDistricts)
    TextView tvDistricts;
    @BindView(R.id.tvContinuousOccurrence)
    TextView tvContinuousOccurrence;
    @BindView(R.id.tvFireType)
    TextView tvFireType;
    @BindView(R.id.tvFireStrength)
    TextView tvFireStrength;
    @BindView(R.id.tvFireNum)
    TextView tvFireNum;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.etReamrk)
    EditText etReamrk;
    @BindView(R.id.bnSave)
    Button bnSave;

    /**
     * 列表
     */
    @BindView(R.id.btn_right)
    ImageView rightIv;

    /**
     * 是否有云烟
     */
    private List<String> mCloudsItems = new ArrayList<>();
    private String[] clouds = new String[]{"有", "无"};

    /**
     * 是否连续出现
     */
    private List<String> mContinuousOccurrenceItems = new ArrayList<>();
    private String[] continuousOccurrence = new String[]{"是", "否"};

    /**
     * 选择地类
     */
    private List<String> mFireTypeItems = new ArrayList<>();
    private String[] fireTypes = new String[]{"耕地", "园地", "林地", "草地"};

    /**
     * 选择火情强度
     */
    private List<String> mFireStrengthItems = new ArrayList<>();
    private String[] fireStrengths = new String[]{"低强度", "中强度", "高强度"};

    /**
     * 所属区县
     */
    private List<String> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();

    private List<String> options2Items_01 = new ArrayList<>();
    private List<String> options2Items_02 = new ArrayList<>();

    /**
     * 采集位置集合
     */
    private String locListStr;

    @Override
    protected int setView() {
        return R.layout.activity_collection_fire_others;
    }

    @Override
    protected void receiveData() {

        //接收参数
        Intent intent = getIntent();
        locListStr = intent.getStringExtra("locListStr");
        Log.i(TAG, "获取采集位置集合：" + locListStr);

        mCloudsItems.clear();
        mCloudsItems.addAll(Arrays.asList(clouds));

        mContinuousOccurrenceItems.clear();
        mContinuousOccurrenceItems.addAll(Arrays.asList(continuousOccurrence));

        mFireTypeItems.clear();
        mFireTypeItems.addAll(Arrays.asList(fireTypes));

        mFireStrengthItems.clear();
        mFireStrengthItems.addAll(Arrays.asList(fireStrengths));

        setAddressData();
    }

    @Override
    protected void initializeView() {
        clicks();

        tvTime.setText(DateUtil.stampToDate(System.currentTimeMillis(), DateUtil.DATE_FORMAT_MM_SS));
        tvFireNum.setText(String.valueOf(new Date().getTime()));
    }

    private void clicks() {
        //返回
        RxView.clicks(backIv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });

        //列表
        RxView.clicks(rightIv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            if (Utils.isLoginOffLine(getApplicationContext())){
                return;
            }
            Intent intentList = new Intent(CollectionFireOthersActivity.this, CollectionListActivity.class);
            intentList.putExtra("type", 1);
            startActivity(intentList);
        });

        //是否有云烟
        RxView.clicks(tvHaveClouds).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etFireLocation);
            loadClouds();
        });

        //火场所属区县
        RxView.clicks(tvDistricts).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etFireLocation);
        });

        //是否连续出现
        RxView.clicks(tvContinuousOccurrence).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etFireLocation);
            loadContinuousOccurrence();
        });

        //火场地类
        RxView.clicks(tvFireType).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etFireLocation);
            loadFireType();
        });

        //火场强度
        RxView.clicks(tvFireStrength).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etFireLocation);
            loadFreStrengths();
        });

        //保存
        RxView.clicks(bnSave).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            saveFireInfo();
        });

        //所属区县
        RxView.clicks(tvDistricts).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            loadAddress();
        });
    }

    private void saveFireInfo() {
        String fireLocation = etFireLocation.getText().toString().trim();
        if (StringUtil.isBlank(fireLocation)) {
            ToastUtils.show("请输入火场位置");
            return;
        }

        String haveClouds = tvHaveClouds.getText().toString().trim();
        if (StringUtil.isBlank(haveClouds)) {
            ToastUtils.show("请选择是否有云烟");
            return;
        }

        String districts = tvDistricts.getText().toString().trim();
        if (StringUtil.isBlank(districts)) {
            ToastUtils.show("请选择所属区县");
            return;
        }

        String continuousOccurrence = tvContinuousOccurrence.getText().toString().trim();
        if (StringUtil.isBlank(continuousOccurrence)) {
            ToastUtils.show("请输入是否连续出现");
            return;
        }

        String fireType = tvFireType.getText().toString().trim();
        if (StringUtil.isBlank(fireType)) {
            ToastUtils.show("请输入地类");
            return;
        }

        String fireStrength = tvFireStrength.getText().toString().trim();
        if (StringUtil.isBlank(fireStrength)) {
            ToastUtils.show("请输入火情强度");
            return;
        }

        String time = tvTime.getText().toString().trim();

        String fireNum = tvFireNum.getText().toString().trim();
        if (StringUtil.isBlank(fireNum)) {
            ToastUtils.show("请输入火场编号");
            return;
        }

        String reamrk = etReamrk.getText().toString().trim();


        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", drUid);
        maps.put("token", token);
        maps.put("firelocation", fireLocation);
        maps.put("cloudsstatus", haveClouds(haveClouds));
        maps.put("district", districts);
        maps.put("iscontinuity", haveContinuousOccurrence(continuousOccurrence));
        maps.put("firesitetype", haveFireType(fireType));
        maps.put("firesity", haveFreStrengths(fireStrength));
        maps.put("firenumber", fireNum);
        maps.put("remake", reamrk);
        maps.put("locationSet", locListStr);//位置集合

        int isOnline = PrefsUtil.getInt(context, CommonKey.ISONLINE);
        if (isOnline == 0) {
            FireInfoModel fireInfoModel = new FireInfoModel();
            fireInfoModel.setFirelocation(fireLocation);
            fireInfoModel.setCloudsstatus(haveClouds(haveClouds));
            fireInfoModel.setIscontinuity(haveContinuousOccurrence(continuousOccurrence));
            fireInfoModel.setFiresitetype(haveFireType(fireType));
            fireInfoModel.setFiresity(haveFreStrengths(fireStrength));
            fireInfoModel.setFirenumber(fireNum);
            fireInfoModel.setRemake(reamrk);
            fireInfoModel.setDistrict(districts);

            if (fireInfoModel.save()) {
                ToastUtils.show("保存成功");
            } else {
                ToastUtils.show("保存失败");
            }
            finish();
        } else {
            showPd();
            presenter.fireInformationInsert(maps);
        }
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.FIRE_INFOMATION_INSERT:
                FireInfoModel fireInfoModel = (FireInfoModel) model;
                if (null != fireInfoModel) {
                    ToastUtils.show(msg == null ? "保存成功" : msg);

                    //保存成功后，跳转列表
                    Intent intentList0 = new Intent(CollectionFireOthersActivity.this, CollectionListActivity.class);
                    intentList0.putExtra("type", 1);
                    startActivity(intentList0);

                    finish();
                }
                break;

            default:
                break;
        }
        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        hidePd();
        ToastUtils.show(message == null ? "网络异常" : message);
    }


    /**
     * 是否有云烟
     */
    OptionsPickerView pvCloudsOptions;
    private int mCloudsPosition;

    private void loadClouds() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvCloudsOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mCloudsItems.get(options1);
                mCloudsPosition = options1;
                tvHaveClouds.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择是否有云烟");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCloudsOptions.returnData();
                                pvCloudsOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCloudsOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvCloudsOptions.setPicker(mCloudsItems);//添加数据
        pvCloudsOptions.show();
    }

    private String haveClouds(String clouds) {
        String c = "";
        if (clouds.equals("有")) {
            c = "0";
        } else {
            c = "1";
        }
        return c;
    }

    /**
     * 是否连续出现
     */
    OptionsPickerView pvContinuousOccurrenceOptions;
    private int mContinuousOccurrencePosition;

    private void loadContinuousOccurrence() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvContinuousOccurrenceOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mContinuousOccurrenceItems.get(options1);
                mContinuousOccurrencePosition = options1;
                tvContinuousOccurrence.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择是否连续出现");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvContinuousOccurrenceOptions.returnData();
                                pvContinuousOccurrenceOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvContinuousOccurrenceOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvContinuousOccurrenceOptions.setPicker(mContinuousOccurrenceItems);//添加数据
        pvContinuousOccurrenceOptions.show();
    }

    private String haveContinuousOccurrence(String clouds) {
        String c = "";
        if (clouds.equals("是")) {
            c = "0";
        } else {
            c = "1";
        }
        return c;
    }

    /**
     * 选择地类
     */
    OptionsPickerView pvFireTypeOptions;
    private int mFireTypePosition;

    private void loadFireType() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvFireTypeOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mFireTypeItems.get(options1);
                mFireTypePosition = options1;
                tvFireType.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择地类");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvFireTypeOptions.returnData();
                                pvFireTypeOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvFireTypeOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvFireTypeOptions.setPicker(mFireTypeItems);//添加数据
        pvFireTypeOptions.show();
    }

    private String haveFireType(String clouds) {
        String c = "";
        //(1 耕地 2 园地 3林地 4草地
        if (clouds.equals("耕地")) {
            c = "1";
        }

        if (clouds.equals("园地")) {
            c = "2";
        }

        if (clouds.equals("林地")) {
            c = "3";
        }

        if (clouds.equals("草地")) {
            c = "4";
        }
        return c;
    }

    /**
     * 选择火情强度
     */
    OptionsPickerView pvFreStrengthOptions;
    private int mFreStrengthsPosition;

    private void loadFreStrengths() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvFreStrengthOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mFireStrengthItems.get(options1);
                mFreStrengthsPosition = options1;
                tvFireStrength.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择火情强度");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvFreStrengthOptions.returnData();
                                pvFreStrengthOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvFreStrengthOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvFreStrengthOptions.setPicker(mFireStrengthItems);//添加数据
        pvFreStrengthOptions.show();
    }

    private String haveFreStrengths(String clouds) {
        String c = "";
        //（1 低强度 2 中强度 3高强度
        if (clouds.equals("低强度")) {
            c = "1";
        }

        if (clouds.equals("中强度")) {
            c = "2";
        }

        if (clouds.equals("高强度")) {
            c = "3";
        }
        return c;
    }

    /**
     * 选择火情强度
     */
    OptionsPickerView pvAddressOptions;
    private int mAddressPosition;

    private void loadAddress() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvAddressOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);
                String tx1 = options2Items.get(options1).get(options2);
//                mAddressPosition = options1;
                tvDistricts.setText(tx + tx1);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择区县");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAddressOptions.returnData();
                                pvAddressOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAddressOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvAddressOptions.setPicker(options1Items, options2Items);//添加数据
        pvAddressOptions.show();
    }

    private void setAddressData() {
        options1Items.clear();
        options2Items.clear();
        options2Items_01.clear();
        options2Items_02.clear();

        options1Items.add("合肥市");

        options1Items.add("六安市");

        //一级1下级的内容数据
        options2Items_01.add("瑶海区");
        options2Items_01.add("蜀山区");
        options2Items_02.add("金安区");
        options2Items_02.add("金寨县");

        //一级2下级的内容数据
        options2Items.add(options2Items_01);
        options2Items.add(options2Items_02);
    }
}
